//
//  LGTTextField.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/13.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit

class LGTTextField: UITextField, UITextFieldDelegate {
    
    var limitCount:Int = -1
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.delegate = self
        //self.addTarget(self, action: #selector(changeAction), for: UIControl.Event.editingChanged)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setTextStyle(textField:UITextField){
        if self.limitCount < 0{
            return
        }
        let length = textField.text?.count ?? 0
        if length == 0{
            return
        }
        
        if self.limitCount < length{
            let text = textField.text
            let text2 = String(text!.prefix(self.limitCount))
            textField.text = text2
        }
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let text = textField.text else{
            return true
        }
        
        if self.limitCount < 0{
            return true
        }
        
        let textLength = text.characters.count + string.characters.count - range.length
        return textLength <= self.limitCount
    }
}



extension String {
    //使用正则表达式替换
    func pregReplace(pattern: String, with: String,
                     options: NSRegularExpression.Options = []) -> String {
        let regex = try! NSRegularExpression(pattern: pattern, options: options)
        return regex.stringByReplacingMatches(in: self, options: [],
                                              range: NSMakeRange(0, self.count),
                                              withTemplate: with)
    }
}
